"use strict";
const electron = require("electron");
const path = require("path");
const fs = require("fs");
const os = require("os");
function _interopNamespaceDefault(e) {
  const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
  if (e) {
    for (const k in e) {
      if (k !== "default") {
        const d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: () => e[k]
        });
      }
    }
  }
  n.default = e;
  return Object.freeze(n);
}
const path__namespace = /* @__PURE__ */ _interopNamespaceDefault(path);
const fs__namespace = /* @__PURE__ */ _interopNamespaceDefault(fs);
const Store = require("electron-store");
const { execSync, exec } = require("child_process");
const store = new Store({
  name: "chrome-manager-settings",
  defaults: {
    chromePath: "",
    dataDir: "",
    shortcutDir: "",
    windowSize: { width: 1200, height: 800 },
    debug: false
  }
});
let mainWindow = null;
let windowCreated = false;
async function waitForServer(url, maxRetries = 5, retryDelay = 500) {
  const { net } = require("electron");
  for (let i = 0; i < maxRetries; i++) {
    try {
      console.log(`检查开发服务器状态... (${i + 1}/${maxRetries}) - ${url}`);
      return new Promise((resolve, reject) => {
        const request = net.request({
          method: "GET",
          url
        });
        const timeout = setTimeout(() => {
          request.abort();
          if (i === maxRetries - 1) {
            reject(new Error("开发服务器连接超时"));
          } else {
            console.log(`开发服务器未就绪，${retryDelay}ms后重试...`);
            setTimeout(() => {
              waitForServer(url, maxRetries - i - 1, retryDelay).then(resolve).catch(reject);
            }, retryDelay);
          }
        }, 2e3);
        request.on("response", (response) => {
          clearTimeout(timeout);
          console.log(`开发服务器已就绪 - 状态码: ${response.statusCode}`);
          resolve();
        });
        request.on("error", (error) => {
          clearTimeout(timeout);
          console.log(`开发服务器连接失败: ${error.message}`);
          if (i === maxRetries - 1) {
            reject(new Error(`开发服务器未就绪: ${error.message}`));
          } else {
            console.log(`${retryDelay}ms后重试...`);
            setTimeout(() => {
              waitForServer(url, maxRetries - i - 1, retryDelay).then(resolve).catch(reject);
            }, retryDelay);
          }
        });
        request.end();
      });
    } catch (error) {
      console.log(`等待开发服务器启动时出错: ${error}`);
      if (i === maxRetries - 1) {
        throw error;
      }
      console.log(`等待开发服务器启动... (${i + 1}/${maxRetries})`);
      await new Promise((resolve) => setTimeout(resolve, retryDelay));
    }
  }
}
function createMainWindow() {
  if (windowCreated) {
    console.log("Window already created, skipping...");
    return;
  }
  const { width, height } = store.get("windowSize");
  mainWindow = new electron.BrowserWindow({
    width,
    height,
    title: "Chrome Manager",
    show: false,
    // 先不显示窗口，避免闪烁
    webPreferences: {
      preload: path__namespace.join(__dirname, "../preload/index.js"),
      nodeIntegration: false,
      contextIsolation: true,
      sandbox: false,
      webSecurity: false,
      // 开发模式下禁用web安全
      allowRunningInsecureContent: true
      // 允许不安全内容
    }
  });
  windowCreated = true;
  if (process.platform === "win32") {
    try {
      process.stdout.write("\x1B[?65;1;4;15h");
    } catch (e) {
    }
  }
  console.log("=== 环境变量检查 ===");
  console.log("NODE_ENV=", process.env.NODE_ENV);
  console.log("VITE_DEV_SERVER_URL=", void 0);
  console.log("==================");
  const devUrl = "http://localhost:3000";
  const showLoadingPage = () => {
    const loadingHTML = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="UTF-8">
        <title>Chrome Manager - 加载中</title>
        <style>
          body {
            margin: 0;
            padding: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            color: white;
          }
          .loading-container {
            text-align: center;
          }
          .loading-spinner {
            width: 50px;
            height: 50px;
            border: 4px solid rgba(255, 255, 255, 0.3);
            border-top: 4px solid white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
          }
          @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
          }
          h1 {
            margin: 0 0 10px 0;
            font-size: 24px;
            font-weight: 300;
          }
          p {
            margin: 0;
            opacity: 0.8;
            font-size: 14px;
          }
        </style>
      </head>
      <body>
        <div class="loading-container">
          <div class="loading-spinner"></div>
          <h1>Chrome Manager</h1>
          <p>正在加载应用...</p>
        </div>
      </body>
      </html>
    `;
    mainWindow.loadURL(`data:text/html,${encodeURIComponent(loadingHTML)}`);
  };
  const loadApp = async () => {
    try {
      if (devUrl) {
        showLoadingPage();
        console.log("开发模式: 加载", devUrl);
        console.log("中文日志测试: 开发服务器连接中...");
        try {
          await waitForServer(devUrl);
        } catch (serverError) {
          console.warn("开发服务器检查失败，等待 3 秒后重试:", serverError);
          await new Promise((resolve) => setTimeout(resolve, 3e3));
        }
        try {
          await mainWindow.loadURL(devUrl);
          console.log("应用加载完成");
          mainWindow.show();
        } catch (loadError) {
          console.error("加载 URL 失败，尝试重新加载:", loadError);
          await new Promise((resolve) => setTimeout(resolve, 2e3));
          await mainWindow.loadURL(devUrl);
          mainWindow.show();
        }
        const debugMode = store.get("debug");
        if (debugMode) {
          mainWindow.webContents.openDevTools();
        }
      }
    } catch (error) {
      console.error("加载应用失败:", error);
      const errorHTML = `
        <!DOCTYPE html>
        <html>
        <head>
          <meta charset="UTF-8">
          <title>Chrome Manager - 错误</title>
          <style>
            body {
              margin: 0;
              padding: 20px;
              background: #f5f5f5;
              font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
              display: flex;
              justify-content: center;
              align-items: center;
              height: 100vh;
            }
            .error-container {
              background: white;
              padding: 40px;
              border-radius: 8px;
              box-shadow: 0 2px 10px rgba(0,0,0,0.1);
              text-align: center;
              max-width: 500px;
            }
            h1 { color: #e74c3c; margin-bottom: 20px; }
            p { color: #666; line-height: 1.6; }
          </style>
        </head>
        <body>
          <div class="error-container">
            <h1>加载失败</h1>
            <p>${error}</p>
          </div>
        </body>
        </html>
      `;
      mainWindow.loadURL(`data:text/html,${encodeURIComponent(errorHTML)}`);
    }
  };
  loadApp();
  mainWindow.on("closed", () => {
    mainWindow = null;
    windowCreated = false;
  });
  mainWindow.on("resize", () => {
    if (mainWindow) {
      const { width: width2, height: height2 } = mainWindow.getBounds();
      store.set("windowSize", { width: width2, height: height2 });
    }
  });
}
async function getChromeProfiles() {
  try {
    const defaultDataDir = store.get("dataDir") || path__namespace.join(electron.app.getPath("userData"), "chrome-environments");
    const profiles = [];
    if (fs__namespace.existsSync(defaultDataDir)) {
      try {
        const folders = fs__namespace.readdirSync(defaultDataDir, { withFileTypes: true });
        for (const folder of folders) {
          if (folder.isDirectory() && folder.name.startsWith("Profile_")) {
            const match = folder.name.match(/Profile_(\d+)/);
            if (match && match[1]) {
              const profileNumber = parseInt(match[1], 10);
              const profilePath = path__namespace.join(defaultDataDir, folder.name);
              const prefsPath = path__namespace.join(profilePath, "Default", "Preferences");
              if (fs__namespace.existsSync(prefsPath)) {
                const shortcutPath = path__namespace.join(profilePath, `Profile_${profileNumber}.lnk`);
                profiles.push({
                  profileNumber,
                  dataDir: profilePath,
                  shortcutPath: fs__namespace.existsSync(shortcutPath) ? shortcutPath : void 0
                });
              }
            }
          }
        }
        profiles.sort((a, b) => a.profileNumber - b.profileNumber);
        console.log(`找到 ${profiles.length} 个创建的Chrome配置文件`);
      } catch (error) {
        console.error("读取配置文件目录失败:", error);
      }
    }
    return profiles;
  } catch (error) {
    console.error("获取Chrome配置文件失败:", error);
    return [];
  }
}
async function getRunningChromeWindows() {
  try {
    if (os.platform() !== "win32") {
      console.log("当前非Windows平台，暂不支持获取Chrome窗口");
      return [];
    }
    console.log("开始获取Chrome窗口信息...");
    const startTime = Date.now();
    const profiles = await getChromeProfiles();
    let chromeProcesses = [];
    try {
      const command = `powershell -ExecutionPolicy Bypass -Command "Get-WmiObject Win32_Process -Filter 'Name=\\"chrome.exe\\"' | Select-Object ProcessId, CommandLine | ConvertTo-Json"`;
      console.log("执行PowerShell命令:", command);
      const output = await new Promise((resolve, reject) => {
        exec(command, { encoding: "utf8", timeout: 5e3 }, (error, stdout, stderr) => {
          if (error) {
            reject(error);
          } else {
            resolve(stdout);
          }
        });
      });
      console.log("PowerShell输出:", output);
      const processes = JSON.parse(output);
      console.log("解析的进程数据:", processes);
      const processArray = Array.isArray(processes) ? processes : [processes];
      chromeProcesses = processArray.map((proc) => ({
        ProcessId: proc.ProcessId,
        CommandLine: proc.CommandLine || ""
      })).filter((proc) => proc.ProcessId && proc.CommandLine);
    } catch (error) {
      console.error("获取Chrome进程信息失败:", error);
      return [];
    }
    chromeProcesses = chromeProcesses.filter((proc) => proc.ProcessId && !isNaN(proc.ProcessId));
    const runningWindows = [];
    for (const profile of profiles) {
      const matchingProcess = chromeProcesses.find((proc) => {
        if (!proc.CommandLine) return false;
        const userDataDirMatch = proc.CommandLine.match(/--user-data-dir=("[^"]+"|[^\s]+)/);
        if (userDataDirMatch && userDataDirMatch[1]) {
          let processUserDataDir = userDataDirMatch[1].replace(/^"|"$/g, "");
          processUserDataDir = path__namespace.resolve(processUserDataDir);
          const profileDataDir = path__namespace.resolve(profile.dataDir);
          return processUserDataDir === profileDataDir;
        }
        return false;
      });
      if (matchingProcess) {
        const pid = matchingProcess.ProcessId;
        try {
          const hwndCommand = `Get-Process -Id ${pid} | Select-Object -ExpandProperty MainWindowHandle`;
          const hwndOutput = await new Promise((resolve, reject) => {
            exec(`powershell -ExecutionPolicy Bypass -Command "${hwndCommand}"`, { encoding: "utf8" }, (error, stdout, stderr) => {
              if (error) {
                reject(error);
              } else {
                resolve(stdout.trim());
              }
            });
          });
          const hwnd = parseInt(hwndOutput) || 0;
          if (hwnd > 0) {
            const titleCommand = `Get-Process -Id ${pid} | Select-Object -ExpandProperty MainWindowTitle`;
            const titleOutput = await new Promise((resolve, reject) => {
              exec(`powershell -ExecutionPolicy Bypass -Command "${titleCommand}"`, { encoding: "utf8" }, (error, stdout, stderr) => {
                if (error) {
                  reject(error);
                } else {
                  resolve(stdout.trim());
                }
              });
            });
            const title = titleOutput || `Chrome Profile ${profile.profileNumber} (运行中)`;
            runningWindows.push({
              id: hwnd,
              // 使用实际的窗口句柄
              title: `Chrome Profile ${profile.profileNumber} (运行中)`,
              pid,
              dataDir: profile.dataDir,
              profileNumber: profile.profileNumber,
              isRunning: true,
              shortcutPath: profile.shortcutPath
            });
          } else {
            runningWindows.push({
              id: -profile.profileNumber,
              title: `Chrome Profile ${profile.profileNumber} (运行中)`,
              pid,
              dataDir: profile.dataDir,
              profileNumber: profile.profileNumber,
              isRunning: true,
              shortcutPath: profile.shortcutPath
            });
          }
        } catch (windowError) {
          console.error("获取窗口信息失败:", windowError);
        }
      }
    }
    const endTime = Date.now();
    console.log(`找到 ${runningWindows.length} 个运行中的Chrome窗口，耗时: ${endTime - startTime}ms`);
    console.log("返回的窗口数据:", runningWindows);
    return runningWindows;
  } catch (error) {
    console.error("获取运行中的Chrome窗口失败:", error);
    return [];
  }
}
electron.ipcMain.handle("get-chrome-windows", async () => {
  try {
    const profiles = await getChromeProfiles();
    const result = profiles.map((profile, index) => ({
      id: -profile.profileNumber,
      number: index + 1,
      title: `Chrome Profile ${profile.profileNumber} (未运行)`,
      pid: 0,
      dataDir: profile.dataDir,
      profileNumber: profile.profileNumber,
      isRunning: false,
      shortcutPath: profile.shortcutPath
    }));
    console.log(`成功获取 ${result.length} 个保存的配置文件数据`);
    return result;
  } catch (error) {
    console.error("获取Chrome配置文件数据失败:", error);
    return [];
  }
});
electron.ipcMain.handle("get-running-chrome-windows", async () => {
  try {
    const storedWindows = Array.from(windowInfoMap.values()).filter((info) => info.isRunning).map((info) => ({
      id: info.hwnd || info.id,
      // 优先使用窗口句柄
      title: info.title || `Chrome Profile ${info.profileNumber} (运行中)`,
      pid: info.pid,
      dataDir: info.dataDir,
      profileNumber: info.profileNumber,
      isRunning: true,
      shortcutPath: info.shortcutPath
    }));
    console.log(`从存储中获取到 ${storedWindows.length} 个窗口信息`);
    if (storedWindows.length > 0) {
      return storedWindows;
    }
    return await getRunningChromeWindows();
  } catch (error) {
    console.error("获取运行中窗口失败:", error);
    return await getRunningChromeWindows();
  }
});
async function findChromeProcessByUserDataDir(userDataDir) {
  try {
    const command = `powershell -ExecutionPolicy Bypass -Command "Get-Process -Name chrome | Select-Object Id | Format-Table -HideTableHeaders"`;
    const output = await new Promise((resolve, reject) => {
      exec(command, { encoding: "utf8" }, (error, stdout, stderr) => {
        if (error) {
          reject(error);
        } else {
          resolve(stdout);
        }
      });
    });
    const lines = output.trim().split("\n");
    const normalizedUserDataDir = path__namespace.resolve(userDataDir);
    for (const line of lines) {
      const pidStr = line.trim();
      if (pidStr && !isNaN(parseInt(pidStr, 10))) {
        const pid = parseInt(pidStr, 10);
        try {
          const cmdLineCommand = `powershell -ExecutionPolicy Bypass -Command "Get-WmiObject Win32_Process -Filter 'ProcessId=${pid}' | Select-Object -ExpandProperty CommandLine"`;
          const cmdLineOutput = await new Promise((resolve, reject) => {
            exec(cmdLineCommand, { encoding: "utf8" }, (error, stdout, stderr) => {
              if (error) {
                reject(error);
              } else {
                resolve(stdout.trim());
              }
            });
          });
          if (cmdLineOutput) {
            const userDataDirMatch = cmdLineOutput.match(/--user-data-dir=(("[^"]+")|[^\s]+)/);
            if (userDataDirMatch && userDataDirMatch[1]) {
              let processUserDataDir = userDataDirMatch[1].replace(/^"|"$/g, "");
              processUserDataDir = path__namespace.resolve(processUserDataDir);
              if (processUserDataDir === normalizedUserDataDir) {
                return pid;
              }
            }
          }
        } catch (cmdLineError) {
          continue;
        }
      }
    }
    return null;
  } catch (error) {
    console.error("查找Chrome进程失败:", error);
    return null;
  }
}
electron.ipcMain.handle("launch-chrome", async (event, args) => {
  try {
    const { userDataDir, port, profileNumber = 0, shortcutPath } = args;
    if (process.platform !== "win32") {
      return { success: false, error: "仅支持Windows系统" };
    }
    if (!fs__namespace.existsSync(userDataDir)) {
      return { success: false, error: "数据目录不存在" };
    }
    let pid = null;
    if (shortcutPath && fs__namespace.existsSync(shortcutPath)) {
      try {
        await new Promise((resolve, reject) => {
          exec(`powershell -ExecutionPolicy Bypass -Command "& '${shortcutPath}'"`, { stdio: "ignore" }, (error, stdout, stderr) => {
            if (error) {
              reject(error);
            } else {
              resolve();
            }
          });
        });
        await new Promise((resolve) => setTimeout(resolve, 500));
        pid = await findChromeProcessByUserDataDir(userDataDir);
        return {
          success: true,
          message: "通过快捷方式启动Chrome",
          pid: pid || void 0
        };
      } catch (shortcutError) {
        console.warn("使用快捷方式启动失败，尝试直接启动:", shortcutError);
      }
    }
    const chromePath = store.get("chromePath");
    if (!chromePath || !fs__namespace.existsSync(chromePath)) {
      const potentialPaths = [
        path__namespace.join(process.env.ProgramFiles || "C:\\Program Files", "Google\\Chrome\\Application\\chrome.exe"),
        path__namespace.join(process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)", "Google\\Chrome\\Application\\chrome.exe"),
        path__namespace.join(process.env.LocalAppData || "C:\\Users\\", process.env.USERNAME || "", "AppData\\Local\\Google\\Chrome\\Application\\chrome.exe")
      ];
      let foundPath = "";
      for (const potentialPath of potentialPaths) {
        if (fs__namespace.existsSync(potentialPath)) {
          foundPath = potentialPath;
          store.set("chromePath", foundPath);
          break;
        }
      }
      if (!foundPath) {
        return { success: false, error: "找不到Chrome浏览器路径" };
      }
    }
    const debugPort = port || 9222 + profileNumber;
    const { spawn } = require("child_process");
    const child = spawn(chromePath, [
      `--user-data-dir=${userDataDir}`,
      `--remote-debugging-port=${debugPort}`,
      "--new-window",
      "--no-first-run",
      "--no-default-browser-check"
    ], { detached: true, stdio: "ignore" });
    pid = child.pid;
    child.unref();
    return {
      success: true,
      message: "Chrome已启动",
      pid
    };
  } catch (error) {
    console.error("启动Chrome失败:", error);
    return { success: false, error: String(error) };
  }
});
electron.ipcMain.handle("get-screens", () => {
  const displays = electron.screen.getAllDisplays();
  return displays.map((display) => ({
    id: display.id,
    x: display.bounds.x,
    y: display.bounds.y,
    width: display.workArea.width,
    height: display.workArea.height,
    primary: display.id === electron.screen.getPrimaryDisplay().id
  }));
});
electron.ipcMain.handle("add-launch-task", async (event, args) => {
  try {
    if (process.platform !== "win32") {
      return { success: false, error: "仅支持Windows系统" };
    }
    const taskId = taskQueue.addTask("launch", args);
    return {
      success: true,
      message: "Chrome启动任务已添加到队列",
      taskId
    };
  } catch (error) {
    console.error("添加启动任务失败:", error);
    return { success: false, error: String(error) };
  }
});
electron.ipcMain.handle("add-close-task", async (event, args) => {
  try {
    if (process.platform !== "win32") {
      return { success: false, error: "仅支持Windows系统" };
    }
    const taskId = taskQueue.addTask("close", args);
    return {
      success: true,
      message: "Chrome关闭任务已添加到队列",
      taskId
    };
  } catch (error) {
    console.error("添加关闭任务失败:", error);
    return { success: false, error: String(error) };
  }
});
electron.ipcMain.handle("add-arrange-task", async (event, args) => {
  try {
    if (process.platform !== "win32") {
      return { success: false, error: "仅支持Windows系统" };
    }
    const taskId = taskQueue.addTask("arrange", args);
    return {
      success: true,
      message: "窗口排列任务已添加到队列",
      taskId
    };
  } catch (error) {
    console.error("添加排列任务失败:", error);
    return { success: false, error: String(error) };
  }
});
electron.ipcMain.handle("get-task-status", async (event, taskId) => {
  try {
    const task = taskQueue.getTask(taskId);
    if (!task) {
      return { success: false, error: "任务不存在" };
    }
    return {
      success: true,
      task
    };
  } catch (error) {
    console.error("获取任务状态失败:", error);
    return { success: false, error: String(error) };
  }
});
electron.ipcMain.handle("get-all-tasks", async () => {
  try {
    const tasks = taskQueue.getAllTasks();
    return {
      success: true,
      tasks
    };
  } catch (error) {
    console.error("获取所有任务失败:", error);
    return { success: false, error: String(error) };
  }
});
const gotTheLock = electron.app.requestSingleInstanceLock();
if (!gotTheLock) {
  electron.app.quit();
} else {
  electron.app.on("second-instance", () => {
    if (mainWindow) {
      if (mainWindow.isMinimized()) {
        mainWindow.restore();
      }
      mainWindow.focus();
    }
  });
  electron.app.once("ready", () => {
    createMainWindow();
  });
  electron.app.on("window-all-closed", () => {
    if (os.platform() !== "darwin") {
      electron.app.quit();
    }
  });
  electron.app.on("activate", () => {
    if (mainWindow === null) {
      createMainWindow();
    }
  });
}
electron.ipcMain.handle("check-admin-permission", () => {
  if (os.platform() !== "win32") {
    return true;
  }
  try {
    const testPath = path__namespace.join(process.env.ProgramFiles || "C:\\Program Files", "chrome-manager-test.txt");
    fs__namespace.writeFileSync(testPath, "test");
    fs__namespace.unlinkSync(testPath);
    return true;
  } catch {
    return false;
  }
});
electron.ipcMain.handle("close-running-chrome-window", async (event, windowId, pid) => {
  try {
    if (os.platform() !== "win32") {
      return { success: false, error: "当前非Windows平台，暂不支持此操作" };
    }
    console.log(`尝试关闭窗口，ID: ${windowId}`);
    if (windowId > 0) {
      const powershellCommand = `Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public class WindowHelper { [DllImport(\\"user32.dll\\")] public static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); }'; $hwnd = [IntPtr]::new(${windowId}); $WM_CLOSE = 0x0010; $success = [WindowHelper]::PostMessage($hwnd, $WM_CLOSE, [IntPtr]::Zero, [IntPtr]::Zero); @{ Success = $success; WindowId = ${windowId} } | ConvertTo-Json`;
      const output = await new Promise((resolve, reject) => {
        exec(`powershell -ExecutionPolicy Bypass -Command "${powershellCommand}"`, { encoding: "utf8" }, (error, stdout, stderr) => {
          if (error) {
            reject(error);
          } else {
            resolve(stdout);
          }
        });
      });
      console.log(`PowerShell输出: ${output}`);
      const result = JSON.parse(output.trim());
      console.log(`尝试关闭窗口 ${windowId}，结果: ${result.Success}`);
      return {
        success: result.Success,
        error: result.Success ? void 0 : "关闭窗口失败"
      };
    } else if (windowId < 0) {
      const profileNumber = Math.abs(windowId);
      console.log(`尝试关闭Chrome进程，Profile: ${profileNumber}`);
      let targetPid = pid;
      if (!targetPid) {
        const defaultDataDir = store.get("dataDir") || path__namespace.join(electron.app.getPath("userData"), "chrome-environments");
        const dataDir = path__namespace.join(defaultDataDir, `Profile_${profileNumber}`);
        const foundPid = await findChromeProcessByUserDataDir(dataDir);
        targetPid = foundPid || void 0;
      }
      if (targetPid) {
        try {
          await new Promise((resolve, reject) => {
            exec(`taskkill /F /PID ${targetPid}`, { stdio: "ignore" }, (error, stdout, stderr) => {
              if (error) {
                reject(error);
              } else {
                resolve();
              }
            });
          });
          console.log(`成功关闭Chrome进程，PID: ${targetPid}`);
          cleanupWindowInfo(windowId);
          return { success: true, message: `已关闭Chrome进程 ${targetPid}` };
        } catch (killError) {
          console.error("关闭进程失败:", killError);
          return { success: false, error: "关闭进程失败" };
        }
      } else {
        console.log(`未找到Profile ${profileNumber}对应的Chrome进程`);
        return { success: false, error: "未找到对应的Chrome进程" };
      }
    } else {
      return { success: false, error: "无效的窗口ID" };
    }
  } catch (error) {
    console.error("操作Chrome窗口失败:", error);
    return { success: false, error: String(error) };
  }
});
async function moveWindowWithAPI(hwnd, x, y, width, height) {
  try {
    console.log(`尝试移动窗口 ${hwnd} 到 (${x}, ${y}) 大小 ${width}x${height}`);
    if (os.platform() !== "win32") {
      console.log("当前非Windows平台，无法移动窗口");
      return false;
    }
    const command = `powershell -ExecutionPolicy Bypass -Command "Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public class Win32 { [DllImport(\\"user32.dll\\")] public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); [DllImport(\\"user32.dll\\")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); }'; $hwnd = [IntPtr]::new(${hwnd}); [Win32]::ShowWindow($hwnd, 9); [Win32]::MoveWindow($hwnd, ${x}, ${y}, ${width}, ${height}, $true)"`;
    const output = await new Promise((resolve, reject) => {
      exec(command, { encoding: "utf8", timeout: 5e3 }, (error, stdout, stderr) => {
        if (error) {
          reject(error);
        } else {
          resolve(stdout);
        }
      });
    });
    console.log(`PowerShell输出: ${output}`);
    return true;
  } catch (error) {
    console.error("使用PowerShell移动窗口失败:", error);
    return false;
  }
}
const windowInfoMap = /* @__PURE__ */ new Map();
class TaskQueue {
  constructor() {
    this.tasks = /* @__PURE__ */ new Map();
    this.runningTasks = /* @__PURE__ */ new Set();
    this.maxConcurrent = 5;
  }
  // 最大并发任务数（增加以支持句柄查找任务）
  addTask(type, data) {
    const id = `${type}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const task = {
      id,
      type,
      data,
      status: "pending",
      progress: 0
    };
    this.tasks.set(id, task);
    this.processQueue();
    return id;
  }
  getTask(id) {
    return this.tasks.get(id);
  }
  getAllTasks() {
    return Array.from(this.tasks.values());
  }
  async processQueue() {
    if (this.runningTasks.size >= this.maxConcurrent) {
      return;
    }
    const pendingTasks = Array.from(this.tasks.values()).filter((task) => task.status === "pending").sort((a, b) => a.startTime || 0 - (b.startTime || 0));
    for (const task of pendingTasks) {
      if (this.runningTasks.size >= this.maxConcurrent) {
        break;
      }
      this.runningTasks.add(task.id);
      task.status = "running";
      task.startTime = Date.now();
      task.progress = 0;
      this.executeTask(task).catch((error) => {
        console.error(`任务 ${task.id} 执行失败:`, error);
        task.status = "failed";
        task.error = String(error);
        task.endTime = Date.now();
        this.runningTasks.delete(task.id);
      });
    }
  }
  async executeTask(task) {
    try {
      let result;
      switch (task.type) {
        case "launch":
          result = await this.executeLaunchTask(task);
          break;
        case "close":
          result = await this.executeCloseTask(task);
          break;
        case "arrange":
          result = await this.executeArrangeTask(task);
          break;
        case "find-handle":
          result = await this.executeFindHandleTask(task);
          break;
        default:
          throw new Error(`未知任务类型: ${task.type}`);
      }
      task.status = "completed";
      task.result = result;
      task.progress = 100;
      task.endTime = Date.now();
      if (mainWindow) {
        mainWindow.webContents.send("task-completed", {
          id: task.id,
          type: task.type,
          status: task.status,
          result
        });
      }
    } catch (error) {
      task.status = "failed";
      task.error = String(error);
      task.endTime = Date.now();
      if (mainWindow) {
        mainWindow.webContents.send("task-failed", {
          id: task.id,
          type: task.type,
          status: task.status,
          error: String(error)
        });
      }
    } finally {
      this.runningTasks.delete(task.id);
      this.processQueue();
    }
  }
  async executeLaunchTask(task) {
    const { userDataDir, port, profileNumber, shortcutPath } = task.data;
    task.progress = 10;
    if (!fs__namespace.existsSync(userDataDir)) {
      throw new Error("数据目录不存在");
    }
    task.progress = 20;
    let pid = null;
    if (shortcutPath && fs__namespace.existsSync(shortcutPath)) {
      try {
        await new Promise((resolve, reject) => {
          exec(`powershell -ExecutionPolicy Bypass -Command "& '${shortcutPath}'"`, { stdio: "ignore" }, (error, stdout, stderr) => {
            if (error) {
              reject(error);
            } else {
              resolve();
            }
          });
        });
        await new Promise((resolve) => setTimeout(resolve, 500));
        pid = await findChromeProcessByUserDataDir(userDataDir);
        task.progress = 80;
        return {
          success: true,
          message: "通过快捷方式启动Chrome",
          pid: pid || void 0
        };
      } catch (shortcutError) {
        console.warn("使用快捷方式启动失败，尝试直接启动:", shortcutError);
      }
    }
    task.progress = 30;
    const chromePath = store.get("chromePath");
    if (!chromePath || !fs__namespace.existsSync(chromePath)) {
      const potentialPaths = [
        path__namespace.join(process.env.ProgramFiles || "C:\\Program Files", "Google\\Chrome\\Application\\chrome.exe"),
        path__namespace.join(process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)", "Google\\Chrome\\Application\\chrome.exe"),
        path__namespace.join(process.env.LocalAppData || "C:\\Users\\", process.env.USERNAME || "", "AppData\\Local\\Google\\Chrome\\Application\\chrome.exe")
      ];
      let foundPath = "";
      for (const potentialPath of potentialPaths) {
        if (fs__namespace.existsSync(potentialPath)) {
          foundPath = potentialPath;
          store.set("chromePath", foundPath);
          break;
        }
      }
      if (!foundPath) {
        throw new Error("找不到Chrome浏览器路径");
      }
    }
    task.progress = 50;
    const debugPort = port || 9222 + profileNumber;
    const { spawn } = require("child_process");
    const child = spawn(chromePath, [
      `--user-data-dir=${userDataDir}`,
      `--remote-debugging-port=${debugPort}`,
      "--new-window",
      "--no-first-run",
      "--no-default-browser-check"
    ], { detached: true, stdio: "ignore" });
    pid = child.pid || 0;
    child.unref();
    task.progress = 70;
    const windowInfo = {
      id: -profileNumber,
      pid: pid || 0,
      dataDir: userDataDir,
      profileNumber,
      isRunning: true,
      launchTime: Date.now()
    };
    windowInfoMap.set(-profileNumber, windowInfo);
    task.progress = 90;
    if (pid && pid > 0) {
      setTimeout(() => {
        taskQueue.addTask("find-handle", {
          pid,
          profileNumber
        });
      }, 2e3);
    }
    return {
      success: true,
      message: "Chrome已启动",
      pid
    };
  }
  async executeCloseTask(task) {
    const { windowId, pid } = task.data;
    task.progress = 10;
    if (windowId > 0) {
      const powershellCommand = `Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public class WindowHelper { [DllImport(\\"user32.dll\\")] public static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); }'; $hwnd = [IntPtr]::new(${windowId}); $WM_CLOSE = 0x0010; $success = [WindowHelper]::PostMessage($hwnd, $WM_CLOSE, [IntPtr]::Zero, [IntPtr]::Zero); @{ Success = $success; WindowId = ${windowId} } | ConvertTo-Json`;
      task.progress = 30;
      const output = await new Promise((resolve, reject) => {
        exec(`powershell -ExecutionPolicy Bypass -Command "${powershellCommand}"`, { encoding: "utf8" }, (error, stdout, stderr) => {
          if (error) {
            reject(error);
          } else {
            resolve(stdout);
          }
        });
      });
      const result = JSON.parse(output.trim());
      task.progress = 80;
      if (result.Success) {
        cleanupWindowInfo(windowId);
      }
      return {
        success: result.Success,
        error: result.Success ? void 0 : "关闭窗口失败"
      };
    } else if (windowId < 0) {
      const profileNumber = Math.abs(windowId);
      task.progress = 30;
      let targetPid = pid;
      if (!targetPid) {
        const defaultDataDir = store.get("dataDir") || path__namespace.join(electron.app.getPath("userData"), "chrome-environments");
        const dataDir = path__namespace.join(defaultDataDir, `Profile_${profileNumber}`);
        const foundPid = await findChromeProcessByUserDataDir(dataDir);
        targetPid = foundPid || void 0;
      }
      task.progress = 60;
      if (targetPid) {
        await new Promise((resolve, reject) => {
          exec(`taskkill /F /PID ${targetPid}`, { stdio: "ignore" }, (error, stdout, stderr) => {
            if (error) {
              reject(error);
            } else {
              resolve();
            }
          });
        });
        cleanupWindowInfo(windowId);
        task.progress = 90;
        return { success: true, message: `已关闭Chrome进程 ${targetPid}` };
      } else {
        throw new Error("未找到对应的Chrome进程");
      }
    } else {
      throw new Error("无效的窗口ID");
    }
  }
  async executeArrangeTask(task) {
    const { type, windowIds, screen: screen2, direction, margin, params } = task.data;
    task.progress = 10;
    if (type === "auto") {
      return await this.executeAutoArrange(task, windowIds, screen2, direction, margin);
    } else if (type === "custom") {
      return await this.executeCustomArrange(task, windowIds, screen2, params);
    } else {
      throw new Error("不支持的排列类型");
    }
  }
  async executeAutoArrange(task, windowIds, screen2, direction, margin) {
    const screenWidth = screen2.workArea.width;
    const screenHeight = screen2.workArea.height;
    const screenX = screen2.workArea.x;
    const screenY = screen2.workArea.y;
    task.progress = 20;
    const count = windowIds.length;
    const cols = Math.ceil(Math.sqrt(count));
    const rows = Math.ceil(count / cols);
    const windowWidth = Math.floor((screenWidth - margin * (cols + 1)) / cols);
    const windowHeight = Math.floor((screenHeight - margin * (rows + 1)) / rows);
    task.progress = 40;
    const positions = [];
    for (let i = 0; i < count; i++) {
      const row = Math.floor(i / cols);
      const col = i % cols;
      const x = screenX + margin + col * (windowWidth + margin);
      const y = screenY + margin + row * (windowHeight + margin);
      positions.push({ x, y, width: windowWidth, height: windowHeight });
    }
    task.progress = 60;
    let successCount = 0;
    const totalWindows = windowIds.length;
    for (let i = 0; i < windowIds.length; i++) {
      const windowId = windowIds[i];
      const position = positions[i];
      try {
        const success = await moveWindowWithAPI(windowId, position.x, position.y, position.width, position.height);
        if (success) {
          successCount++;
        }
      } catch (error) {
        console.error(`移动窗口 ${windowId} 失败:`, error);
      }
      task.progress = 60 + Math.floor((i + 1) / totalWindows * 30);
    }
    task.progress = 100;
    return {
      success: successCount > 0,
      message: `成功排列 ${successCount}/${windowIds.length} 个窗口`,
      arrangedCount: successCount
    };
  }
  async executeCustomArrange(task, windowIds, screen2, params) {
    const { startX, startY, windowWidth, windowHeight, hSpacing, vSpacing, windowsPerRow } = params;
    task.progress = 20;
    let successCount = 0;
    const totalWindows = windowIds.length;
    for (let i = 0; i < windowIds.length; i++) {
      const windowId = windowIds[i];
      const row = Math.floor(i / windowsPerRow);
      const col = i % windowsPerRow;
      const x = startX + col * (windowWidth + hSpacing);
      const y = startY + row * (windowHeight + vSpacing);
      try {
        const success = await moveWindowWithAPI(windowId, x, y, windowWidth, windowHeight);
        if (success) {
          successCount++;
        }
      } catch (error) {
        console.error(`移动窗口 ${windowId} 失败:`, error);
      }
      task.progress = 20 + Math.floor((i + 1) / totalWindows * 70);
    }
    task.progress = 100;
    return {
      success: successCount > 0,
      message: `成功排列 ${successCount}/${windowIds.length} 个窗口`,
      arrangedCount: successCount
    };
  }
  async executeFindHandleTask(task) {
    const { pid, profileNumber } = task.data;
    task.progress = 10;
    try {
      console.log(`异步查找PID ${pid} 的窗口句柄...`);
      const windowHandle = await findWindowHandleByPid(pid);
      task.progress = 50;
      if (windowHandle) {
        const existingInfo = windowInfoMap.get(-profileNumber);
        if (existingInfo) {
          existingInfo.hwnd = windowHandle.hwnd;
          existingInfo.title = windowHandle.title;
          existingInfo.id = windowHandle.hwnd;
          windowInfoMap.set(windowHandle.hwnd, existingInfo);
          windowInfoMap.delete(-profileNumber);
          console.log(`异步成功获取窗口句柄 ${windowHandle.hwnd}，标题: ${windowHandle.title}`);
        }
        task.progress = 100;
        return {
          success: true,
          message: `成功获取窗口句柄 ${windowHandle.hwnd}`,
          hwnd: windowHandle.hwnd,
          title: windowHandle.title
        };
      } else {
        task.progress = 100;
        return {
          success: false,
          message: `PID ${pid} 未找到可见窗口`
        };
      }
    } catch (error) {
      console.error(`异步获取窗口句柄失败:`, error);
      task.progress = 100;
      return {
        success: false,
        error: String(error)
      };
    }
  }
}
const taskQueue = new TaskQueue();
function cleanupWindowInfo(windowId) {
  windowInfoMap.delete(windowId);
  if (windowId < 0) {
    const profileNumber = Math.abs(windowId);
    const entries = Array.from(windowInfoMap.entries());
    for (const [id, info] of entries) {
      if (info.profileNumber === profileNumber) {
        windowInfoMap.delete(id);
        break;
      }
    }
  }
}
async function findWindowHandleByPid(pid) {
  try {
    console.log(`开始查找PID ${pid} 的窗口句柄...`);
    const simpleCommand = `Get-Process -Id ${pid} | Select-Object Id, ProcessName, MainWindowTitle | ConvertTo-Json`;
    const output = await new Promise((resolve, reject) => {
      exec(`powershell -ExecutionPolicy Bypass -Command "${simpleCommand}"`, { encoding: "utf8" }, (error, stdout, stderr) => {
        if (error) {
          reject(error);
        } else {
          resolve(stdout.trim());
        }
      });
    });
    console.log(`PowerShell输出: ${output}`);
    if (output && output !== "") {
      try {
        const processInfo = JSON.parse(output);
        console.log(`找到进程: ID=${processInfo.Id}, 名称=${processInfo.ProcessName}, 窗口标题=${processInfo.MainWindowTitle}`);
        if (processInfo.MainWindowTitle && processInfo.MainWindowTitle.trim() !== "") {
          const hwndCommand = `Get-Process -Id ${pid} | Select-Object -ExpandProperty MainWindowHandle`;
          const hwndOutput = await new Promise((resolve, reject) => {
            exec(`powershell -ExecutionPolicy Bypass -Command "${hwndCommand}"`, { encoding: "utf8" }, (error, stdout, stderr) => {
              if (error) {
                reject(error);
              } else {
                resolve(stdout.trim());
              }
            });
          });
          const hwnd = parseInt(hwndOutput) || 0;
          if (hwnd > 0) {
            return {
              hwnd,
              title: processInfo.MainWindowTitle
            };
          }
        }
        console.log(`PID ${pid} 没有找到可见窗口`);
        return null;
      } catch (parseError) {
        console.error(`解析PID ${pid} 的进程信息失败:`, parseError);
        console.log(`原始输出: ${output}`);
        return null;
      }
    } else {
      console.log(`PID ${pid} 没有找到进程`);
      return null;
    }
  } catch (error) {
    console.error(`查找PID ${pid} 的窗口句柄失败:`, error);
    return null;
  }
}
electron.ipcMain.handle("launch-chrome-profile", async (event, windowId) => {
  try {
    if (os.platform() !== "win32") {
      return { success: false, error: "当前非Windows平台，暂不支持此操作" };
    }
    if (windowId >= 0) {
      return { success: false, error: "无效的配置文件ID" };
    }
    const profileNumber = Math.abs(windowId);
    const defaultDataDir = store.get("dataDir") || path__namespace.join(electron.app.getPath("userData"), "chrome-environments");
    const dataDir = path__namespace.join(defaultDataDir, `Profile_${profileNumber}`);
    let chromePath = store.get("chromePath");
    if (!chromePath || !fs__namespace.existsSync(chromePath)) {
      console.log("无法找到有效的Chrome可执行文件路径");
      return { success: false, error: "Chrome可执行文件路径未设置或无效，请手动指定Chrome安装位置" };
    }
    if (!fs__namespace.existsSync(dataDir)) {
      return { success: false, error: `配置文件目录不存在: ${dataDir}` };
    }
    console.log(`启动Chrome配置文件 ${profileNumber}`);
    const { spawn } = require("child_process");
    const child = spawn(chromePath, [
      `--user-data-dir=${dataDir}`,
      `--remote-debugging-port=${9222 + profileNumber}`,
      "--no-first-run",
      "--no-default-browser-check",
      "--new-window"
    ], {
      detached: true,
      stdio: "ignore"
    });
    const pid = child.pid;
    child.unref();
    console.log(`已直接启动Chrome配置文件 ${profileNumber}，PID: ${pid}`);
    const windowInfo = {
      id: -profileNumber,
      // 使用负数ID作为配置文件ID
      pid,
      dataDir,
      profileNumber,
      isRunning: true,
      launchTime: Date.now()
    };
    windowInfoMap.set(-profileNumber, windowInfo);
    setTimeout(() => {
      taskQueue.addTask("find-handle", {
        pid,
        profileNumber
      });
    }, 3e3);
    return {
      success: true,
      message: `已启动Chrome配置文件 ${profileNumber}`,
      pid
    };
  } catch (error) {
    console.error("启动Chrome配置文件失败:", error);
    return { success: false, error: String(error) };
  }
});
async function autoArrangeWindows(windowIds, screen2, direction, margin) {
  try {
    console.log(`自动排列 ${windowIds.length} 个窗口`);
    const screenWidth = screen2.workArea.width;
    const screenHeight = screen2.workArea.height;
    const screenX = screen2.workArea.x;
    const screenY = screen2.workArea.y;
    console.log(`屏幕工作区: ${screenWidth}x${screenHeight} at (${screenX}, ${screenY})`);
    const count = windowIds.length;
    const cols = Math.ceil(Math.sqrt(count));
    const rows = Math.ceil(count / cols);
    const windowWidth = Math.floor((screenWidth - margin * (cols + 1)) / cols);
    const windowHeight = Math.floor((screenHeight - margin * (rows + 1)) / rows);
    console.log(`布局: ${rows}行 x ${cols}列, 窗口大小: ${windowWidth}x${windowHeight}`);
    const positions = [];
    for (let i = 0; i < count; i++) {
      const row = Math.floor(i / cols);
      const col = i % cols;
      const x = screenX + margin + col * (windowWidth + margin);
      const y = screenY + margin + row * (windowHeight + margin);
      positions.push({ x, y, width: windowWidth, height: windowHeight });
    }
    let successCount = 0;
    for (let i = 0; i < windowIds.length; i++) {
      const windowId = windowIds[i];
      const position = positions[i];
      try {
        console.log(`使用Windows API移动窗口 ${windowId} 到 (${position.x}, ${position.y})`);
        const success = await moveWindowWithAPI(windowId, position.x, position.y, position.width, position.height);
        if (success) {
          successCount++;
          console.log(`窗口 ${windowId} 移动成功到 (${position.x}, ${position.y})`);
        } else {
          console.log(`窗口 ${windowId} 移动失败`);
        }
      } catch (error) {
        console.error(`移动窗口 ${windowId} 失败:`, error);
      }
    }
    console.log(`成功排列 ${successCount}/${windowIds.length} 个窗口`);
    return {
      success: successCount > 0,
      message: `成功排列 ${successCount}/${windowIds.length} 个窗口`,
      arrangedCount: successCount
    };
  } catch (error) {
    console.error("自动排列窗口失败:", error);
    return { success: false, error: String(error) };
  }
}
async function customArrangeWindows(windowIds, params, screen2) {
  try {
    console.log(`自定义排列 ${windowIds.length} 个窗口`);
    const { startX, startY, windowWidth, windowHeight, hSpacing, vSpacing, windowsPerRow } = params;
    let successCount = 0;
    for (let i = 0; i < windowIds.length; i++) {
      const windowId = windowIds[i];
      const row = Math.floor(i / windowsPerRow);
      const col = i % windowsPerRow;
      const x = startX + col * (windowWidth + hSpacing);
      const y = startY + row * (windowHeight + vSpacing);
      try {
        console.log(`使用Windows API移动窗口 ${windowId} 到 (${x}, ${y})`);
        const success = await moveWindowWithAPI(windowId, x, y, windowWidth, windowHeight);
        if (success) {
          successCount++;
          console.log(`窗口 ${windowId} 移动成功到 (${x}, ${y})`);
        } else {
          console.log(`窗口 ${windowId} 移动失败`);
        }
      } catch (error) {
        console.error(`移动窗口 ${windowId} 失败:`, error);
      }
    }
    console.log(`成功排列 ${successCount}/${windowIds.length} 个窗口`);
    return {
      success: successCount > 0,
      message: `成功排列 ${successCount}/${windowIds.length} 个窗口`,
      arrangedCount: successCount
    };
  } catch (error) {
    console.error("自定义排列窗口失败:", error);
    return { success: false, error: String(error) };
  }
}
electron.ipcMain.handle("arrange-windows", async (event, params) => {
  try {
    if (os.platform() !== "win32") {
      return { success: false, error: "当前非Windows平台，暂不支持窗口排列" };
    }
    console.log("开始排列窗口，参数:", params);
    const { type, screenId, direction, margin, windowIds } = params;
    if (!windowIds || windowIds.length === 0) {
      return { success: false, error: "没有选择要排列的窗口" };
    }
    const displays = electron.screen.getAllDisplays();
    const screens = displays.map((display) => ({
      id: display.id,
      x: display.bounds.x,
      y: display.bounds.y,
      width: display.bounds.width,
      height: display.bounds.height,
      primary: display.id === electron.screen.getPrimaryDisplay().id,
      workArea: {
        x: display.workArea.x,
        y: display.workArea.y,
        width: display.workArea.width,
        height: display.workArea.height
      }
    }));
    if (!screens || screens.length === 0) {
      return { success: false, error: "无法获取屏幕信息" };
    }
    const targetScreen = screens[screenId] || screens[0];
    console.log("目标屏幕:", targetScreen);
    const validWindowIds = windowIds.filter((id) => id > 0);
    if (validWindowIds.length === 0) {
      return { success: false, error: "没有运行中的窗口可以排列，请先启动Chrome窗口" };
    }
    console.log(`有效窗口句柄: ${validWindowIds}`);
    if (type === "auto") {
      return await autoArrangeWindows(validWindowIds, targetScreen, direction, margin);
    } else if (type === "custom") {
      return await customArrangeWindows(validWindowIds, params, targetScreen);
    } else {
      return { success: false, error: "不支持的排列类型" };
    }
  } catch (error) {
    console.error("排列窗口失败:", error);
    return { success: false, error: String(error) };
  }
});
electron.ipcMain.handle("start-sync", async (event, windowIds) => {
  try {
    return { success: true };
  } catch (error) {
    console.error("开始同步失败:", error);
    return { success: false, error: String(error) };
  }
});
electron.ipcMain.handle("stop-sync", async () => {
  try {
    return { success: true };
  } catch (error) {
    console.error("停止同步失败:", error);
    return { success: false, error: String(error) };
  }
});
electron.ipcMain.handle("create-shortcut", async (event, options) => {
  try {
    return { success: true };
  } catch (error) {
    console.error("创建快捷方式失败:", error);
    return { success: false, error: String(error) };
  }
});
electron.ipcMain.handle("restart-as-admin", async () => {
  try {
    return { success: true };
  } catch (error) {
    console.error("以管理员权限重启失败:", error);
    return { success: false, error: String(error) };
  }
});
electron.ipcMain.handle("get-settings", () => {
  return store.store;
});
electron.ipcMain.handle("save-settings", (event, settings) => {
  try {
    Object.assign(store.store, settings);
    return { success: true };
  } catch (error) {
    console.error("保存设置失败:", error);
    return { success: false, error: String(error) };
  }
});
electron.ipcMain.handle("quit-app", () => {
  electron.app.quit();
  return { success: true };
});
electron.ipcMain.handle("select-chrome-executable", async () => {
  const { dialog } = require("electron");
  try {
    const result = await dialog.showOpenDialog(mainWindow, {
      title: "选择Chrome可执行文件",
      properties: ["openFile"],
      filters: [
        { name: "可执行文件", extensions: ["exe"] },
        { name: "所有文件", extensions: ["*"] }
      ]
    });
    if (!result.canceled && result.filePaths.length > 0) {
      return result.filePaths[0];
    }
    return null;
  } catch (error) {
    console.error("选择Chrome可执行文件失败:", error);
    return null;
  }
});
electron.ipcMain.handle("select-directory", async () => {
  const { dialog } = require("electron");
  try {
    const result = await dialog.showOpenDialog(mainWindow, {
      title: "选择目录",
      properties: ["openDirectory"]
    });
    if (!result.canceled && result.filePaths.length > 0) {
      return result.filePaths[0];
    }
    return null;
  } catch (error) {
    console.error("选择目录失败:", error);
    return null;
  }
});
electron.ipcMain.handle("get-default-paths", () => {
  electron.app.getPath("appData");
  const userData = electron.app.getPath("userData");
  const tempDir = electron.app.getPath("temp");
  const desktopDir = electron.app.getPath("desktop");
  let defaultChromePath = "";
  if (os.platform() === "win32") {
    const potentialPaths = [
      path__namespace.join(process.env.ProgramFiles || "C:\\Program Files", "Google\\Chrome\\Application\\chrome.exe"),
      path__namespace.join(process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)", "Google\\Chrome\\Application\\chrome.exe"),
      path__namespace.join(process.env.LocalAppData || "C:\\Users\\", process.env.USERNAME || "", "AppData\\Local\\Google\\Chrome\\Application\\chrome.exe")
    ];
    for (const chromePath of potentialPaths) {
      if (fs__namespace.existsSync(chromePath)) {
        defaultChromePath = chromePath;
        break;
      }
    }
  }
  const defaultDataDir = path__namespace.join(userData, "chrome-environments");
  const defaultShortcutDir = desktopDir;
  return {
    chromePath: defaultChromePath,
    dataDir: defaultDataDir,
    shortcutDir: defaultShortcutDir,
    tempDir
  };
});
electron.ipcMain.handle("create-chrome-environment", async (event, config) => {
  try {
    const { chromePath, dataDir, debugPort, createDesktopShortcut, profileNumber } = config;
    if (!fs__namespace.existsSync(dataDir)) {
      fs__namespace.mkdirSync(dataDir, { recursive: true });
      console.log(`创建数据目录: ${dataDir}`);
    }
    const defaultPrefs = {
      profile: {
        default_content_settings: {
          cookies: 1,
          images: 1,
          javascript: 1,
          plugins: 1,
          popups: 1,
          geolocation: 0,
          notifications: 0
        },
        default_content_setting_values: {
          camera: 2,
          microphone: 2,
          midi_sysex: 0
        },
        name: `Profile ${profileNumber}`,
        avatar_index: profileNumber % 8
        // 使用不同的头像索引
      },
      browser: {
        check_default_browser: false
      },
      homepage: "about:blank",
      startup_urls: ["about:blank"]
    };
    const prefsDir = path__namespace.join(dataDir, "Default");
    if (!fs__namespace.existsSync(prefsDir)) {
      fs__namespace.mkdirSync(prefsDir, { recursive: true });
    }
    const prefsPath = path__namespace.join(prefsDir, "Preferences");
    fs__namespace.writeFileSync(prefsPath, JSON.stringify(defaultPrefs, null, 2), "utf-8");
    console.log(`创建默认首选项文件: ${prefsPath}`);
    const localState = {
      browser: {
        last_redirect_origin_mapping: {},
        show_home_button: true
      },
      profile: {
        last_used: "Default"
      }
    };
    const localStatePath = path__namespace.join(dataDir, "Local State");
    fs__namespace.writeFileSync(localStatePath, JSON.stringify(localState, null, 2), "utf-8");
    console.log(`创建Local State文件: ${localStatePath}`);
    const target = chromePath;
    const args = [
      `--user-data-dir=${dataDir}`,
      `--remote-debugging-port=${debugPort}`,
      "--no-first-run",
      "--no-default-browser-check"
    ];
    const argsString = args.join(" ");
    const createShortcut = async (shortcutPath) => {
      try {
        const shell = require("electron").shell;
        if (process.platform === "win32") {
          const wscriptPath = path__namespace.join(process.env.WINDIR || "C:\\Windows", "System32", "wscript.exe");
          const tempVbsPath = path__namespace.join(electron.app.getPath("temp"), `create_shortcut_${Date.now()}.vbs`);
          const vbsContent = `
            Set objShell = CreateObject("WScript.Shell")
            Set objShortcut = objShell.CreateShortcut("${shortcutPath.replace(/\\/g, "\\\\")}")
            objShortcut.TargetPath = "${target.replace(/\\/g, "\\\\")}"
            objShortcut.Arguments = "${argsString.replace(/"/g, '"')}"
            objShortcut.Description = "Chrome Profile ${profileNumber}"
            objShortcut.WorkingDirectory = "${path__namespace.dirname(target).replace(/\\/g, "\\\\")}"
            objShortcut.IconLocation = "${target.replace(/\\/g, "\\\\")},0"
            objShortcut.Save
          `;
          fs__namespace.writeFileSync(tempVbsPath, vbsContent, "utf-8");
          await new Promise((resolve, reject) => {
            exec(`${wscriptPath} ${tempVbsPath}`, { stdio: "ignore" }, (error, stdout, stderr) => {
              if (error) {
                reject(error);
              } else {
                resolve();
              }
            });
          });
          fs__namespace.unlinkSync(tempVbsPath);
          console.log(`成功创建快捷方式: ${shortcutPath}`);
        } else {
          console.log(`当前平台 ${process.platform} 暂不支持创建快捷方式`);
        }
      } catch (error) {
        console.error(`创建快捷方式失败 ${shortcutPath}:`, error);
        throw error;
      }
    };
    const dataDirShortcutPath = path__namespace.join(dataDir, `Chrome Profile ${profileNumber}.lnk`);
    await createShortcut(dataDirShortcutPath);
    if (createDesktopShortcut) {
      const desktopPath = electron.app.getPath("desktop");
      const desktopShortcutPath = path__namespace.join(desktopPath, `Chrome Profile ${profileNumber}.lnk`);
      await createShortcut(desktopShortcutPath);
    }
    return { success: true, profileNumber };
  } catch (error) {
    console.error("创建Chrome环境失败:", error);
    throw new Error(`创建Chrome环境失败: ${error instanceof Error ? error.message : String(error)}`);
  }
});
